﻿using HardwareWebApi.Model;
using MySql.Data.MySqlClient;
using System.Collections.Generic;

using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;


namespace HardwareWebApi.Connector
{
    public class Conn
    {
        private string connString;
        private string path;
        
        public Conn()
        {
            //System.Configuration
            //var builder = new ConfigurationBuilder().AddJsonFile(path + "appsettings.json");
            //var builder = new ConfigurationBuilder();
            //var configuration = builder.Build();
            //connString = configuration["ConnString"];

            connString = @"server=localhost;uid=root;pwd=aa123456;database=vbislife; sslmode=none";
        }

        public void setConfig(IHostingEnvironment hostingEviroment)
        {
            path = hostingEviroment.ContentRootFileProvider.ToString();
            System.Diagnostics.Debug.Write("this is mypath", path);
        }

        public List<User> UserList()
        {
            List<User> allUser = new List<User>();

            using (MySqlConnection connMysql = new MySqlConnection(connString))
            {
                using (MySqlCommand cmmd = connMysql.CreateCommand())
                {
                    cmmd.CommandText = "select * from userlist";
                    cmmd.CommandType = System.Data.CommandType.Text;

                    cmmd.Connection = connMysql;

                    connMysql.Open();

                    using (MySqlDataReader reader = cmmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            allUser.Add(new User { id = reader.GetInt32(reader.GetOrdinal("id")),
                                                    name=reader.GetString(reader.GetOrdinal("name")),
                                                    password=reader.GetString(reader.GetOrdinal("password"))
                                                 });
                        }
                    }

                    connMysql.Close();
                }
            }
        return allUser;
        }
    }
}
